import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {HttpService} from '../../../service/http.service';
import {ModalController, AlertController, NavController} from '@ionic/angular';
import {RadioPickModelComponent} from '../../../components/radio-pick-model/radio-pick-model.component';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import { TransferService } from 'src/app/service/transfer.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-patient-personal-center',
    templateUrl: './patient-personal-center.page.html',
    styleUrls: ['./patient-personal-center.page.scss'],
})
export class PatientPersonalCenterPage implements OnInit {
    personName = '';
    englishName = '';
    passport = '';
    personSex = '';
    personAge = '';
    personTel = '';
    personEmail = '';
    personMH = '';
    personDD = '';
    avatarUrl = '';
    genderId = 0;
    sexBox = [{value: 1, label: 'Male'}, {value: 2, label: 'Female'}];
    sysLang = '';
    constructor(
        private router: Router,
        private httpService: HttpService,
        private navController: NavController,
        public modalController: ModalController,
        public alertController: AlertController,
        private imagePicker: ImagePicker,
        private transferSrv: TransferService,
        private translate: TranslateService,
    ) {
    }

    ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    }

    async ionViewDidEnter() {
        await this.getPersonInfo();
    }

    async toInfoEdit(type) {
        const editParams: any = {
            dataType: type
        };
        if (type === 'name') {
            editParams.value = this.personName;
        } else if (type === 'englishName') {
            editParams.value = this.englishName;
        } else if (type === 'passport') {
            editParams.value = this.passport;
        } else if (type === 'age') {
            editParams.value = this.personAge;
        } else if (type === 'phone') {
            editParams.value = this.personTel;
        } else if (type === 'email') {
            editParams.value = this.personEmail;
        } else if (type === 'MH') {
            editParams.value = this.personMH;
        } else if (type === 'DD') {
            editParams.value = this.personDD;
        }
        await this.router.navigate(['patient-person-edit'], {
            queryParams: editParams
        });
    }

    public async getPersonInfo() {
        const aUserId = localStorage.getItem('userId');
        const result: any = await this.httpService.get()
            .setPath('/user/patientInfo/' + aUserId)
            .request();
        const aData = result.data;
        if (result.status === 0) {
            if (!!aData.nickname) {
                this.personName = aData.nickname;
            }

            if (!!aData.english_name) {
                this.englishName = aData.english_name;
            }

            if (!!aData.passport) {
                this.passport = aData.passport;
            }

            if (!!aData.gender) {
                this.personSex = this.sexBox[aData.gender - 1].label;
                this.genderId = aData.gender;
            }

            if (!!aData.age) {
                this.personAge = aData.age;
            }

            if (!!aData.phone) {
                this.personTel = aData.phone;
            }

            if (!!aData.email) {
                this.personEmail = aData.email;
            }

            if (!!aData.medical_history) {
                this.personMH = aData.medical_history;
            }

            if (!!aData.medical_desc) {
                this.personDD = aData.medical_desc;
            }

            if (!!aData.avatar_url) {
                this.avatarUrl = aData.avatar_url;
            }
        }
    }

    public async selectGender() {
        const modal = await this.modalController.create({
            component: RadioPickModelComponent,
            componentProps: {
                title: 'Sex',
                labelProp: 'label',
                selectValue: this.genderId,
                dataList: [...this.sexBox]
            }
        });
        await modal.present();
        const {data} = await modal.onDidDismiss();
        if (!!data) {
            this.saveData('gender', data.value);
        }
    }

    public async saveData(aKey, aParam) {
        const aUserId = localStorage.getItem('userId');
        const postBody = {};
        postBody[aKey] = aParam;
        const result: any = await this.httpService.put()
            .setPath('/user/patientUpdate/' + aUserId)
            .setBody({
                ...postBody
            })
            .request();
        if (result.status === 0) {
            const aMessage = this.sysLang === 'en-us' ? 'Save Success' : '保存成功';
            const aText = this.sysLang === 'en-us' ? 'Confirm' : '确定';
            const alert = await this.alertController.create({
                message: aMessage,
                buttons: [
                    {
                        text: aText,
                        handler: () => {
                            this.getPersonInfo();
                        }
                    }
                ]
            });
            await alert.present();
        }
    }

    public async selectImg() {
        const aUserId = localStorage.getItem('userId');
        try {
            const result = await this.imagePicker.getPictures({ maximumImagesCount: 1, quality: 20 });
            const uploadResult = await this.transferSrv.setPath('/upload/file')
                .setFile(result)
                .parseFile()
                .setFieldName('user')
                .setParams({
                    uploadType: 'avatar',
                    userId: aUserId
                })
                .upload();
            if (uploadResult.status === 0) {
                this.avatarUrl = uploadResult.data.resUrl;
            }
        } catch (e) {
            if (HttpService.EnvIndex < 2) {
                alert(JSON.stringify(e));
            }
        }
    }
}
